package demo4;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;

public class MyTimer {
    BlockingQueue<MyTask> queue=new PriorityBlockingQueue<>();
    public MyTimer(){
        Thread thread =new Thread(()->{
            while (true) {
                try {
                    MyTask myTask=queue.take();
                    if(System.currentTimeMillis()>=myTask.getTime()){
                        myTask.run();
                    }else{
                        queue.put(myTask);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
    }
    public void schedule(MyTask myTask,long delay) throws InterruptedException {
        if(myTask==null) throw new IllegalArgumentException("任务不能为空");
        myTask.setTime(delay);
        queue.put(myTask);
    }
}
